/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.resource.web;

import com.lczyfz.istep.common.config.Global;
import com.lczyfz.istep.common.constants.ResourceConstants;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.utils.FormatHtmlUtil;
import com.lczyfz.istep.common.utils.JsonModel;
import com.lczyfz.istep.common.utils.StringUtils;
import com.lczyfz.istep.common.utils.SysUploadUtils;
import com.lczyfz.istep.common.web.BaseController;
import com.lczyfz.istep.modules.resource.entity.ResourceFile;
import com.lczyfz.istep.modules.resource.entity.ResourceQuestion;
import com.lczyfz.istep.modules.resource.entity.ResourceQuestionAnswer;
import com.lczyfz.istep.modules.resource.entity.ResourceQuestionOption;
import com.lczyfz.istep.modules.resource.service.*;
import com.lczyfz.istep.modules.scene.entity.SceneEnvironment;
import com.lczyfz.istep.modules.scene.service.SceneEnvironmentService;
import com.lczyfz.istep.modules.sys.service.SystemService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * 考题管理Controller
 * @author dh
 * @version 2017-01-15
 */
@Controller
@RequestMapping(value = "${adminPath}/resource/resourceQuestion")
public class ResourceQuestionController extends BaseController {

	@Autowired
	private ResourceQuestionService resourceQuestionService;
	@Autowired
	private ResourceQuestionAnswerService resourceQuestionAnswerService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private SceneEnvironmentService sceneEnvironmentService;
	@Autowired
	private ResourceFileService resourceFileService;
	@Autowired
	private ResourceQuestionOptionService resourceQuestionOptionService;
	@Autowired
	private ResourcePaperQuestionService resourcePaperQuestionService;

	@ModelAttribute
	public ResourceQuestion get(@RequestParam(required=false) String id) {
		ResourceQuestion entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = resourceQuestionService.get(id);
		}
		if (entity == null){
			entity = new ResourceQuestion();
		}
		return entity;
	}
	
	@RequiresPermissions("resource:resourceQuestion:view")
	@RequestMapping(value = {"list", ""})
	public String list(ResourceQuestion resourceQuestion, HttpServletRequest request, HttpServletResponse response, Model model) {

		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");

		}
		else
		{
			model.addAttribute("isSuperAdmin", "false");
		}
		Page<ResourceQuestion> page = resourceQuestionService.findPage(new Page<ResourceQuestion>(request, response), resourceQuestion);
		model.addAttribute("page", page);
		return "modules/resource/resourceQuestionList";
	}

	@RequiresPermissions("resource:resourceQuestion:view")
	@RequestMapping(value = "form")
	public String form(ResourceQuestion resourceQuestion, Model model) {
		//List<ResourceQuestionAnswer> findAnswerlist = resourceQuestionAnswerService.findAnswerList();

  		//model.addAttribute("findAnswerList",findAnswerlist);

		if(systemService.isSuperAdmin())
		{
			model.addAttribute("isSuperAdmin", "true");
		}else
			model.addAttribute("isSuperAdmin", "false");
		logger.debug("isSuperAdmin==dh: [{}]", systemService.isSuperAdmin());

		//查询教学实验环境列表
		SceneEnvironment sceneEnvironment=new SceneEnvironment();
		List<SceneEnvironment> sceneEnvironmentList=sceneEnvironmentService.findList(sceneEnvironment);
		logger.debug("sceneEnvironmentList===：[{}]",sceneEnvironmentList.size());

		if(resourceQuestion!=null&&resourceQuestion.getId()!=null&&!resourceQuestion.getId().equals(""))
		{
			ResourceFile resourceFile =new ResourceFile();
			resourceFile.setResourceId(resourceQuestion.getId());
			resourceFile.setType(ResourceConstants.fileTypeQuestionAttachment);
			List<ResourceFile> ls= resourceFileService.findList(resourceFile);
			String attachmentUrl="";
			if(ls.size()>0)
			{
				attachmentUrl=ls.get(0).getName();
				logger.debug("attachmentUrl=== [{}]", attachmentUrl);
				model.addAttribute("attachmentUrl", attachmentUrl);
			}

			ResourceQuestionAnswer questionAnswer=new ResourceQuestionAnswer();
			questionAnswer.setQuestionId(resourceQuestion.getId());

			List<ResourceQuestionAnswer> questionAnswerList=resourceQuestionAnswerService.findList(questionAnswer);
			String answer="";
			for (int i = 0; i < questionAnswerList.size(); i++)
			{
				answer = answer + " " + questionAnswerList.get(i).getAnswer();
			}
			if (resourceQuestion.getQuestionType().equals("1")) {
				model.addAttribute("questionTypeTwo", resourceQuestion.getQuestionType());
				model.addAttribute("questionAnswerList", questionAnswerList);
			}


			if(!resourceQuestion.getQuestionType().equals("3"))
			{
				ResourceQuestionOption resourceQuestionOption=new ResourceQuestionOption();
				resourceQuestionOption.setQuestionId(resourceQuestion.getId());
				List<ResourceQuestionOption> optionList=resourceQuestionOptionService.findList(resourceQuestionOption);
				model.addAttribute("option", optionList.get(0));

			}

			model.addAttribute("answer", answer);

		}
		model.addAttribute("sceneEnvironmentList", sceneEnvironmentList);
		model.addAttribute("resourceQuestion", resourceQuestion);
		return "modules/resource/resourceQuestionForm";
	}

	@RequiresPermissions("resource:resourceQuestion:edit")
	@RequestMapping(value = "save")
	public String save(ResourceQuestion resourceQuestion, Model model, RedirectAttributes redirectAttributes,String answer,String questionAnswer,String optionA,String optionB,String optionC,String optionD) {
		if (!beanValidator(model, resourceQuestion)){
			return form(resourceQuestion, model);
		}
		logger.debug("answer: [{}]", answer);
		logger.debug("questionAnswer: [{}]", questionAnswer);
		if(resourceQuestion.getDocument()!=null)
		{
			resourceQuestion.setDocument(FormatHtmlUtil.formatHtml(StringEscapeUtils.unescapeHtml4(resourceQuestion.getDocument())));
			logger.debug("dingh===document=2=" + resourceQuestion.getDocument());

		}
		ResourceQuestion temp=resourceQuestionService.findQuestionByName(resourceQuestion);

		if (resourceQuestionService.get(resourceQuestion) == null) {
			logger.debug("新增===");
			if (temp != null  && temp.getQuestionName().equals(resourceQuestion.getQuestionName())) {
				addMessage(redirectAttributes, "新增考题'" + resourceQuestion.getQuestionName() + "'失败，该考题已存在");

			} else {
				resourceQuestionService.save(resourceQuestion);
				resourceQuestionOptionService.save(resourceQuestion,optionA,optionB,optionC,optionD);

				if(resourceQuestion.getAttachment()!=null&&!resourceQuestion.getAttachment().equals(""))
				{
					logger.debug("videoFileId：[{}]",resourceQuestion.getAttachment());
					ResourceFile resourceFile = resourceFileService.get(resourceQuestion.getAttachment());
					resourceFile.setResourceId(resourceQuestion.getId());
					resourceFileService.update(resourceFile);
					logger.debug("更新文件表resourceId");
				}
				logger.debug("ID: [{}]", resourceQuestion.getId());
				if (questionAnswer != null && !questionAnswer.equals(""))
					resourceQuestionAnswerService.save(resourceQuestion,questionAnswer);
				addMessage(redirectAttributes, "保存考题管理成功");
			}
		}else {
			logger.debug("修改==="+questionAnswer);
			resourceQuestionService.save(resourceQuestion);
			resourceQuestionOptionService.save(resourceQuestion,optionA,optionB,optionC,optionD);
			if(resourceQuestion.getAttachment()!=null&&!resourceQuestion.getAttachment().equals(""))
			{
				ResourceFile temp1=new ResourceFile();
				temp1.setResourceId(resourceQuestion.getId());
				temp1.setType(ResourceConstants.fileTypeQuestionAttachment);
				List<ResourceFile> list= resourceFileService.findList(temp1);
				for(int i=0;i<list.size();i++)
				{
					if(!list.get(i).getId().equals(resourceQuestion.getAttachment())) {
						resourceFileService.delete(list.get(i));
						File file=new File(list.get(i).getLocalUrl());
						if(file.exists()) {
							file.delete();
							logger.debug("删除文件：[{}]", list.get(i).getLocalUrl());
						}
					}
				}
				logger.debug("videoFileId：[{}]",resourceQuestion.getAttachment());
				ResourceFile resourceFile = resourceFileService.get(resourceQuestion.getAttachment());
				resourceFile.setResourceId(resourceQuestion.getId());
				resourceFileService.update(resourceFile);
				logger.debug("更新文件表resourceId");
			}
			logger.debug("ID: [{}]", resourceQuestion.getId());
			if (questionAnswer != null && !questionAnswer.equals(""))
				resourceQuestionAnswerService.save(resourceQuestion,questionAnswer);
			addMessage(redirectAttributes, "修改考题管理成功");
		}

		return "redirect:"+Global.getAdminPath()+"/resource/resourceQuestion/?repage";
	}
	
	@RequiresPermissions("resource:resourceQuestion:edit")
	@RequestMapping(value = "delete")
	public String delete(ResourceQuestion resourceQuestion, RedirectAttributes redirectAttributes) {
		resourceQuestionService.delete(resourceQuestion);
//		resourceQuestionOptionService.delete(resourceQuestionOption);
		addMessage(redirectAttributes, "删除考题管理成功");
		return "redirect:"+Global.getAdminPath()+"/resource/resourceQuestion/?repage";
	}

	@RequiresPermissions("resource:resourceQuestion:edit")
	@RequestMapping(value = "detail")
	public String detail(ResourceQuestion resourceQuestion, RedirectAttributes redirectAttributes, Model model) {

		logger.debug("QuestionID: [{}]", resourceQuestion.getId());

		ResourceQuestionAnswer resourceQuestionAnswer=new ResourceQuestionAnswer();
		resourceQuestionAnswer.setQuestionId(resourceQuestion.getId());
		List<ResourceQuestionAnswer> answerList=resourceQuestionAnswerService.findList(resourceQuestionAnswer);
		String questionAnswer="";
		for (int i=0;i<answerList.size();i++)
		{
			questionAnswer=questionAnswer+" "+answerList.get(i).getAnswer();
		}
		resourceQuestion=resourceQuestionService.get(resourceQuestion);
		if(resourceQuestion.getEnvironmentId()!=null&&!resourceQuestion.getEnvironmentId().equals(""))
			resourceQuestion.setEnvironmentName(sceneEnvironmentService.get(resourceQuestion.getEnvironmentId()).getEnvironmentName());

		ResourceFile resourceFile =new ResourceFile();
		resourceFile.setResourceId(resourceQuestion.getId());
		resourceFile.setType(ResourceConstants.fileTypeQuestionAttachment);
		List<ResourceFile> ls= resourceFileService.findList(resourceFile);
		String attachmentUrl="";
		if(ls.size()>0)
		{
			attachmentUrl=ls.get(0).getName();
			logger.debug("attachmentUrl=== [{}]", attachmentUrl);
			model.addAttribute("attachmentUrl", attachmentUrl);
		}

		model.addAttribute("questionAnswer", questionAnswer);
		model.addAttribute("resourceQuestion", resourceQuestion);

		return "modules/resource/resourceQuestionDetail";
	}

	@ResponseBody
	@RequestMapping(value = "getQuestionNameById", method = RequestMethod.POST)
	public  List<Map<String, String>> getQuestionNameById(String QuestionId) {
		System.out.println("----" + QuestionId);

		logger.debug("==Evan==QuestionId: "+ QuestionId);

		List<Map<String, String>> QuestionListName = new ArrayList<>();

		if(QuestionId==null || QuestionId.equals("")){
			QuestionListName = null;
		}else{
			String[] QuestionListId = QuestionId.split(",");
			for(String aQuestionListId : QuestionListId){
				Map<String, String> QuestionMap = new HashMap<>();
				QuestionMap.put("id",aQuestionListId);
				QuestionMap.put("name",resourceQuestionService.get(aQuestionListId).getQuestionName());
				QuestionMap.put("type",resourceQuestionService.get(aQuestionListId).getQuestionType());
				String temp = resourceQuestionService.get(aQuestionListId).getQuestionType();
				if(String.valueOf(temp)=="0"){
//					QuestionMap.put("score",resourcePaperQuestionService.get(aQuestionListId).getQuestionScore());
				}

				QuestionListName.add(QuestionMap);
			}
		}
		return QuestionListName;
	}

	/**
	 * 上传附件
	 * 上传附件
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
	public JsonModel fileUpload(HttpServletRequest request) {
		logger.debug("上传附件===");

		JsonModel jsonModel = new JsonModel();
		SysUploadUtils sysUploadUtils=new SysUploadUtils();
//		ResourceFile file=sysUploadUtils.uploadFile(request,ResourceConstants.videoMateria);

		ResourceFile resourceFile=null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			//将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			//获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				//一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					logger.debug("上传===");
					resourceFile=sysUploadUtils.saveFile(file, ResourceConstants.fileTypeQuestionAttachment);
				}
			}
		}
		logger.debug("上传附件成功===");
		logger.debug("上传===" + sysUploadUtils.getMessage());

		if(resourceFile!=null&&sysUploadUtils.isSuccess())
		{
			resourceFile.setType(ResourceConstants.fileTypeQuestionAttachment);
			resourceFileService.save(resourceFile);
			List<String> fileInfo=new ArrayList<>();
			fileInfo.add(resourceFile.getId());
			fileInfo.add(resourceFile.getUrl());
			jsonModel.setSuccess(true);
			jsonModel.setMsg(sysUploadUtils.getMessage());
			jsonModel.setDataObj(fileInfo);
			return jsonModel;
		}else {
			jsonModel.setMsg(sysUploadUtils.getMessage());
			jsonModel.setSuccess(false);
			return jsonModel;
		}
	}



/*
	@ResponseBody
	@RequestMapping(value = "getQuestionNameById", method = RequestMethod.POST)
	public  List<Map<String, String>> getQuestionNameById(String QuestionId) {
		System.out.println("----" + QuestionId);

		logger.debug("==Evan==QuestionId: "+ QuestionId);

		List<Map<String, String>> QuestionListName = new ArrayList<>();

		if(QuestionId==null || QuestionId.equals("")){
			QuestionListName = null;
		}else{
			String[] QuestionListId = QuestionId.split(",");
			for(String aQuestionListId : QuestionListId){
				Map<String, String> QuestionMap = new HashMap<>();
				QuestionMap.put("id",aQuestionListId);
				QuestionMap.put("name",resourceQuestionService.get(aQuestionListId).getQuestionName());
				QuestionMap.put("type",resourceQuestionService.get(aQuestionListId).getQuestionType());
				QuestionMap.put("score",resourceQuestionService.get(aQuestionListId).getQuestionScore());
				QuestionListName.add(QuestionMap);
			}
		}
		return QuestionListName;
		}
*/




//	@ResponseBody
//	@RequestMapping(value = "getQuestionNameById")
//	public List<Map<String, String>> getQuestionNameById(String QuestionId){
//
//	}
//


}